package com.fs.luban.security.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.fs.luban.common.support.JsonResult;
import com.fs.luban.util.RequestUtils;
import com.fs.luban.util.mapper.JsonMapper;

/**
 * @title 登陆失败Handler
 * @Description 增强登陆失败 ajax的支持
 * @author fengshi
 */
public class LubanLoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		if (RequestUtils.isAjax(request)) {
			response.setStatus(HttpStatus.OK.value());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			PrintWriter printWriter = response.getWriter();
			// 回填信息
			JsonResult result = new JsonResult(String.valueOf(HttpStatus.UNAUTHORIZED.value()),	exception.getLocalizedMessage());
			result.setSuccess(false);
			printWriter.write(JsonMapper.nonDefaultMapper().toJson(result));
			printWriter.flush();
			printWriter.close();
			return;
		}
		super.onAuthenticationFailure(request, response, exception);
	}

}
